/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.javanile.chess.stone;

/**
 *
 * @author totalinnovation
 */
public class Fen {
    public static int[] parse(String fen) {
	int[] b = new int[Stone.start.length];
	int i=0,x=0,y=0,s=0;
	while(i<fen.length()) {
	    char c = fen.charAt(i);
	    if (false) {
	    } else if (s == 0) {
		// parse position
		switch(c) {
		    case '/':y++;x=0;break;
		    case 'p':b[y*8+x]=Stone.bp;x++;break;
		    case 'n':b[y*8+x]=Stone.bn;x++;break;
		    case 'b':b[y*8+x]=Stone.bb;x++;break;
		    case 'r':b[y*8+x]=Stone.br;x++;break;
		    case 'q':b[y*8+x]=Stone.bq;x++;break;
		    case 'k':b[y*8+x]=Stone.bk;x++;break;
		    case 'P':b[y*8+x]=Stone.wp;x++;break;
		    case 'N':b[y*8+x]=Stone.wn;x++;break;
		    case 'B':b[y*8+x]=Stone.wb;x++;break;
		    case 'R':b[y*8+x]=Stone.wr;x++;break;
		    case 'Q':b[y*8+x]=Stone.wq;x++;break;
		    case 'K':b[y*8+x]=Stone.wk;x++;break;
		    case '1':x=x+1;break;
		    case '2':x=x+2;break;
		    case '3':x=x+3;break;
		    case '4':x=x+4;break;
		    case '5':x=x+5;break;
		    case '6':x=x+6;break;
		    case '7':x=x+7;break;
		    case '8':x=x+8;break;
		    case ' ':s=1;
		}
	    } else if (s==1) {
		// parse turn
		switch(c) {
		    case 'w':b[Stone.turn]=Stone.white;break;
		    case 'b':b[Stone.turn]=Stone.black;break;
		    case ' ':s=2;
		}
	    } else if (s==2) {
		// parse castling
		switch(c) {
		    case 'q':b[Stone.bqsc]=Stone.yes;x++;break;
		    case 'k':b[Stone.bksc]=Stone.yes;x++;break;
		    case 'Q':b[Stone.wksc]=Stone.yes;x++;break;
		    case 'K':b[Stone.wksc]=Stone.yes;x++;break;
		    case ' ':s=3;
		}
	    } else if (s==3) {
		// parse en-passant
		switch(c) {
		    case '-':break;
		    case ' ':s=4;
		}
	    } else if (s==4) {
		// countend halfmove after capture or pawn move
		switch(c) {
		    case '-':break;
		    case ' ':s=5;
		}
	    } else if (s==5) {
		// countend moves at beginning
		switch(c) {
		    case '-':break;
		    case ' ':s=6;
		}
	    }
	    i++;
	}
	return b;
    }
}
